package com.julius.design.suanfa.linked;

import java.util.List;
import java.util.Stack;

/**
 * @author julius
 * @date 2021-10-20 上午 9:59
 * <p>
 *     反向打印链表
 * </p>
 */
public class ReversePrint {

    /**
     * 反向打印链表
     * @param head 链表
     * @return 数组
     */
    public static int[] reversePrint(ListNode head){
        //临界条件
        if(head == null){
            return new int[0];
        }
        Stack<Integer> stack = new Stack<>();
        //遍历链表，放入栈中，利用栈的先进后出原则进行链表翻转
        ListNode cur = head;
        while (cur != null){
            stack.push(cur.val);
            cur = cur.next;
        }

        int[] result = new int[stack.size()];
        int i = 0;
        while (!stack.isEmpty()){
            result[i] = stack.pop();
            i++;
        }
        return result;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        l1.next = l2;
        l2.next = l3;

        int[] ints = reversePrint(l1);
        for (int i = 0; i <ints.length ; i++) {
            System.out.println(ints[i]);

        }

    }



    public static class ListNode{
        int val;
        ListNode next;
        ListNode(int x){
            val = x;
        }

    }
}
